/**
 * 流的用法
 *  行读取器
 * 
 * 流动模式不经过缓存区
 */
let fs = require("fs")

let EventEmitter = require("events")
let util = require('util')
let NEW_LINE = 0x0A; // /n 换行
let RETURN = 0x0D; // /r 回车
function LineReader(path){
    EventEmitter.call(this)
    this._reader = fs.createReadStream(path)
    this.on("newListener", (type,listener)=>{
        // 如果说你添加了newLine和监听, 那么就开始读取内容并按行发射数据
        if(type == 'newLine'){
            let buffers = []
            // 缓存区填满事件 readable
            this._reader.on('readable', ()=>{
                let char; //Buffer 是只有一个字节的buffer
                while(null != (char = this._reader.read(1))){
                    switch(char[0]){
                        case NEW_LINE:
                            this.emit('newLine', Buffer.from(buffers))
                            buffers.length = 0
                            break;
                        case RETURN:
                            this.emit('newLine', Buffer.from(buffers))
                            buffers.length = 0
                            // 往后再读一个字节
                            let nChar = this._reader.read(1)
                            if(nChar[0] != NEW_LINE){
                                buffers.push(nChar[0]);
                            }
                            break;
                        default:
                            buffers.push(char[0])
                            break;
                    }
                }
            })
        }
    })
}

util.inherits(LineReader, EventEmitter)






